#!/usr/bin/env python3
"""
客户管理字段迁移脚本
将原有客户字段迁移到新的字段结构
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from app.models.customer import Customer, CustomerLog
from datetime import datetime

def migrate_customer_fields():
    """迁移客户字段"""
    app = create_app()
    with app.app_context():
        print("开始迁移客户字段...")
        
        # 获取所有客户
        customers = Customer.query.all()
        print(f"找到 {len(customers)} 个客户记录")
        
        # 备份当前数据
        backup_data = []
        for customer in customers:
            backup_data.append({
                'id': customer.id,
                'name': customer.name,
                'customer_number': customer.customer_number,
                'old_source': getattr(customer, 'source', None),
                'old_industry': getattr(customer, 'industry', None),
                'old_scale': getattr(customer, 'scale', None),
                'old_type': getattr(customer, 'type', None),
                'old_status': getattr(customer, 'status', None),
                'old_address': getattr(customer, 'address', None),
                'old_phone': getattr(customer, 'phone', None),
                'old_email': getattr(customer, 'email', None),
                'old_website': getattr(customer, 'website', None),
                'old_remarks': getattr(customer, 'remarks', None),
                'old_estimated_amount': getattr(customer, 'estimated_amount', None),
                'old_estimated_close_date': getattr(customer, 'estimated_close_date', None),
                'manager_id': customer.manager_id,
                'converted_from_lead_id': customer.converted_from_lead_id,
                'conversion_date': customer.conversion_date,
                'conversion_reason': customer.conversion_reason,
                'created_at': customer.created_at,
                'updated_at': customer.updated_at
            })
        
        # 为没有客户编号的客户生成编号
        for customer in customers:
            if not customer.customer_number:
                customer.customer_number = Customer.generate_customer_number()
        
        # 执行字段迁移
        for i, customer in enumerate(customers):
            # 设置默认值
            customer.category = '普通客户'  # 默认客户分类
            customer.location = '华东'  # 默认客户归属地
            
            # 如果原来的source字段存在，则迁移到新的source字段
            if backup_data[i]['old_source']:
                customer.source = backup_data[i]['old_source']
            else:
                customer.source = '网站'  # 默认客户来源
            
            # 保留原有的地址信息
            if backup_data[i]['old_address']:
                customer.address = backup_data[i]['old_address']
            
            # 记录迁移日志
            log = CustomerLog(
                customer_id=customer.id,
                operation_type='字段迁移',
                operation_content=f'客户字段迁移：保留客户名称、编号、地址等信息；新增客户分类、归属地等字段；移除行业、规模、类型、状态、电话、邮箱、网站、备注、预估金额、预估成交日期等字段',
                operator_id=1  # 系统管理员ID，实际使用时需要替换
            )
            db.session.add(log)
        
        # 提交更改
        try:
            db.session.commit()
            print("客户字段迁移完成！")
            
            # 验证迁移结果
            print("\n验证迁移结果...")
            for customer in customers[:5]:  # 只验证前5个客户
                print(f"客户ID: {customer.id}, 名称: {customer.name}, 编号: {customer.customer_number}")
                print(f"  分类: {customer.category}, 归属地: {customer.location}, 来源: {customer.source}")
                print(f"  地址: {customer.address}")
                
        except Exception as e:
            db.session.rollback()
            print(f"迁移失败: {str(e)}")
            return False
        
        return True

if __name__ == '__main__':
    success = migrate_customer_fields()
    if success:
        print("\n客户字段迁移成功完成！")
    else:
        print("\n客户字段迁移失败，请检查错误信息！")
        sys.exit(1)